package com.heima.search.service.impl;

import com.heima.common.es.ElasticSearchTemplate;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.SearchService;
import com.heima.search.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

/**
 * @author lzy
 * @date 2022/7/25 15:37
 */
@Service
@Slf4j
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ElasticSearchTemplate elasticSearchTemplate;
    @Autowired
    private ApUserSearchService apUserSearchService;

    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        //先获取需要用到的参数
        int pageSize = dto.getPageSize();
        String searchWords = dto.getSearchWords();
        Date minBehotTime = dto.getMinBehotTime();
        int pageNum = dto.getPageNum();

        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        Integer userId = user.getId();
        if (userId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        //1.关键词搜索
        //title包含关键字 or content包含关键字
        QueryStringQueryBuilder stringQueryBuilder = elasticSearchTemplate.getStringQueryBuilder(searchWords, Operator.OR, "title", "content");
        //2.日期范围搜索
        Map<String, Object> condition = new HashMap<>();
        condition.put("lt",minBehotTime);
        RangeQueryBuilder rangeQueryBuilder = elasticSearchTemplate.getRangeBuilder("publishTime", condition);
        //布尔查询
        Map<String, AbstractQueryBuilder> boolBuilder = new HashMap<>();
        boolBuilder.put("must",stringQueryBuilder);
        boolBuilder.put("filter",rangeQueryBuilder);
        BoolQueryBuilder boolQueryBuilder = elasticSearchTemplate.getBoolQueryBuilder(boolBuilder);
        //3.高亮设置   "<font style='color: red; font-size: inherit;'>title</font>"
        HighlightBuilder highlightBuilder = elasticSearchTemplate.getHighlightBuilder("title", "<font style='color: red; font-size: inherit;'>", "</font>");

        //5.执行search方法
        SearchResponse search = elasticSearchTemplate.search("app_info_article", boolQueryBuilder, highlightBuilder, pageNum, pageSize, "publishTime", SortOrder.DESC);
        //记录本次搜索的关键字
        apUserSearchService.insert(searchWords,userId);

        SearchHits hits = search.getHits();
        SearchHit[] hits1 = hits.getHits();
        if (ArrayUtils.isEmpty(hits1)){
            return ResponseResult.okResult("");
        }

        List<Map<String, Object>> resultList = new ArrayList<>();
        for (SearchHit hit : hits1) {
            if (hit == null){
                continue;
            }
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            resultList.add(sourceAsMap);
        }

        return ResponseResult.okResult(resultList);
    }
}
